package com.ai.notices.web.controller.busi;

import java.text.DecimalFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ai.notices.common.constants.Constants;
import com.ai.notices.common.util.DateUtils;
import com.ai.notices.common.util.ObjectCopyUtil;
import com.ai.notices.common.util.PagedResult;
import com.ai.notices.common.util.StringUtil;
import com.ai.notices.dao.mysql.model.AuthStaff;
import com.ai.notices.dao.mysql.model.GdsInfo;
import com.ai.notices.dao.mysql.model.GdsInfoImp;
import com.ai.notices.dao.mysql.model.GdsPic;
import com.ai.notices.service.interfaces.IGdsInfoSV;
import com.ai.notices.service.resp.GdsInfoResp;
import com.ai.notices.utils.mongo.ImangeServer;
import com.ai.notices.web.FileUtils;
import com.ai.notices.web.controller.vo.GdsInfoVO;
import com.ai.notices.web.system.AppBaseController;
import com.ai.notices.web.system.excel.ExcelExport;
import com.ai.notices.web.system.util.StaffSessionUtil;
import com.alibaba.fastjson.JSONObject;

/**
 * Created by huangzh on 17/6/17.
 */
@Controller
@RequestMapping(value = "/gds")
public class GdsController extends AppBaseController {
    private static final Logger log = Logger.getLogger(GdsController.class);

    @Autowired
    private IGdsInfoSV gdsInfoSV;
    /*
    * 功能描述:进入商品列表页面
    * 开发人员:huangzh5
    * */
    @RequestMapping(value="/init")
    public String init() throws Exception{
        return "/busi/gds/gds-init"; //返回页面
    }

    @RequestMapping(value = "/gdsList")
    public String gdsList(Model model, GdsInfoVO vo, Integer pageNo, Integer pageSize) throws Exception {
        PagedResult<GdsInfo> pageResult = new PagedResult<GdsInfo>();
        pageResult = gdsInfoSV.queryGdsInfoByPage(vo, pageNo, pageSize);
        model.addAttribute("data", pageResult);
        return "/busi/gds/list/gds-list";
    }

    /**
     * 功能描述:删除关键词
     * 开发人员:huangzh5
     */
    @RequestMapping(value="/delGdsInfo", method= RequestMethod.POST)
    @ResponseBody
    public Map delGdsInfo(@RequestParam("idLst") String[] idLst) {
        Map retMap = new HashMap();
        if(null == idLst || idLst.length <= 0){
            retMap.put(Constants.RetFlag.FLAG,Constants.RetFlag.ERROR);
            retMap.put(Constants.RetFlag.MSG,"系统异常，请重新尝试!");
        }else{
            try {
                gdsInfoSV.updateGdsInfo(Arrays.asList(idLst));
                retMap.put(Constants.RetFlag.FLAG,Constants.RetFlag.SUCCESS);
                retMap.put(Constants.RetFlag.MSG,"删除成功!");
            } catch (Exception e) {
                log.error(e.toString());
                retMap.put(Constants.RetFlag.FLAG,Constants.RetFlag.ERROR);
                retMap.put(Constants.RetFlag.MSG,"系统异常，请重新尝试!");
            }
        }

        return retMap;
    }

    @RequestMapping(value = { "/gds_import_init" })
    public String gdsImportInit(Model model) throws Exception {

        return "/busi/gds/gds-import";
    }

    @RequestMapping(value = { "/save_gds" }, method = { RequestMethod.POST })
    @ResponseBody
    public JSONObject saveGds(@RequestParam("batchId") String batchId, Model model,
                                HttpServletRequest request, HttpServletResponse response) throws Exception {
        AuthStaff authStaff = StaffSessionUtil.getStaffInfo(request.getSession());
        JSONObject ret = new JSONObject();
        try {
            gdsInfoSV.saveGdsInfo(batchId, authStaff);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
        }
        ret.put("flag", true);
        ret.put("msg", batchId);
        return ret;
    }

    @RequestMapping(value = { "/gds_import" }, method = { RequestMethod.POST })
    @ResponseBody
    public JSONObject gdsImport(@RequestParam("gdsFile") MultipartFile mfile, Model model,
                                  HttpServletRequest request, HttpServletResponse response) throws Exception {
        AuthStaff authStaff = StaffSessionUtil.getStaffInfo(request.getSession());
        JSONObject ret = new JSONObject();
        List<List<Map<String, String>>> gdsInfos = FileUtils.file2List(mfile);
        if (CollectionUtils.isEmpty(gdsInfos) || CollectionUtils.isEmpty(gdsInfos.get(0))) {
            ret.put("flag", false);
            ret.put("msg", "上传的文件格式不正确（如：文件为空、导入文件不支持）");
            return ret;
        }
        String batchId = FileUtils.getId();
        try {
            gdsInfoSV.saveGdsInfoImp(gdsInfos.get(0), batchId, authStaff);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
        }
        ret.put("flag", true);
        ret.put("msg", batchId);
        return ret;
    }

    @RequestMapping(value = { "/gds_import_list" }, method = { RequestMethod.POST })
    public String gdsImportList(Model model, GdsInfoImp imp, Integer pageNo, Integer pageSize) throws Exception {
        PagedResult<GdsInfoImp> pageResult = gdsInfoSV.queryGdsInfoImpByPage(imp, pageNo, pageSize);
        model.addAttribute("data", pageResult);
        return "/busi/gds/gds-import-list";
    }

    @RequestMapping(value = { "/gds_import_success_list" }, method = { RequestMethod.POST })
    public String gdsImportSuccessList(Model model, GdsInfoImp imp, Integer pageNo, Integer pageSize) throws Exception {
        PagedResult<GdsInfoImp> pageResult = gdsInfoSV.queryGdsInfoImpByPage(imp, pageNo, pageSize);
        model.addAttribute("data", pageResult);
        return "/busi/gds/gds-import-success-list";
    }

    @RequestMapping(value = { "/gds_import_fail_list" }, method = { RequestMethod.POST })
    public String gdsImportFailList(Model model, GdsInfoImp imp, Integer pageNo, Integer pageSize) throws Exception {
        PagedResult<GdsInfoImp> pageResult = gdsInfoSV.queryGdsInfoImpByPage(imp, pageNo, pageSize);
        model.addAttribute("data", pageResult);
        return "/busi/gds/gds-import-fail-list";
    }

    @RequestMapping(value = { "/gds_export" }, method = { RequestMethod.POST })
    public void gdsExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取查询参数
        String batchId = request.getParameter("batchId");
        String state = request.getParameter("state");
        String gdsName = request.getParameter("gdsName");
        String gdsCode = request.getParameter("gdsCode");
        String brand = request.getParameter("brand");

        GdsInfo gdsInfo = new GdsInfo();
        if(StringUtil.isNotBlank(batchId)){
            gdsInfo.setBatchId(batchId);
        }
        if(StringUtil.isNotBlank(state)){
            gdsInfo.setState(state);
        }
        if(StringUtil.isNotBlank(gdsName)){
            gdsInfo.setGdsName(gdsName);
        }
        if(StringUtil.isNotBlank(gdsCode)){
            gdsInfo.setGdsCode(gdsCode);
        }
        if(StringUtil.isNotBlank(brand)){
            gdsInfo.setBrand(brand);
        }

        List<GdsInfo> tmpList = new ArrayList<GdsInfo>();
        tmpList = gdsInfoSV.queryGdsInfos(gdsInfo);

        List<String> titleList = new ArrayList<String>();
        titleList.add("序号");
        titleList.add("商品货号");
        titleList.add("品牌");
        titleList.add("商品名称");
        titleList.add("规格型号");
        titleList.add("销售价");

        List<List<String>> dataList = new ArrayList<List<String>>();
        if(null != tmpList && tmpList.size() > 0){
            int i = 0;
            for(GdsInfo tmpGdsInfo : tmpList){
                i++;
                List<String> data = new ArrayList<String>();
                data.add(String.valueOf(i));
                data.add(String.valueOf(tmpGdsInfo.getGdsId()));
                data.add(tmpGdsInfo.getBrand());
                data.add(tmpGdsInfo.getGdsName());
                data.add(tmpGdsInfo.getSpec());

                String price = String.valueOf(tmpGdsInfo.getPrice());
                if(StringUtil.isBlank(price)){
                    price = "0";
                }else{
                    if(price.length() <= 3){
                        float num= (float)tmpGdsInfo.getPrice()/100;
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        price = df.format(num);//返回的是String类型
                    }else{
                        price = String.valueOf(tmpGdsInfo.getPrice()/100);
                    }
                }
                data.add(price);

                dataList.add(data);
            }
        }

        String xlsName = "导出产品表"+DateUtils.getDateString(DateUtils.YYYYMMDDHHMMSS)+".xls";

        ExcelExport.exportExcelFile(titleList, dataList, xlsName, 0, request, response);
    }
    @RequestMapping(value="/editGdsInfo")
    public String editGdsInfo(Model model, GdsInfoVO vo) throws Exception {
    	model.addAttribute("imageUrl", ImangeServer.imageUrl);
    	if(StringUtils.isNotEmpty(vo.getId()+"")){
    		GdsInfoResp gdsinfo = gdsInfoSV.queryGdsInfosByPk(vo.getId());
    		model.addAttribute("gdsInfo", gdsinfo);
    	}
    	return "/busi/gds/editGdsInfo";
    }
    @RequestMapping(value="/updateGdsInfo")
    @ResponseBody
    public Map<String,String> updateGdsInfo(Model model, GdsInfoVO vo) throws Exception{
    	Map<String,String> ret = new HashMap<>();
    	ret.put("flag", "fail");
    	if(StringUtils.isNotEmpty(vo.getId()+"")){
    		if(vo.getPrice()!=null){
    			vo.setPrice(vo.getPrice()*100);
    		}
    		gdsInfoSV.updateGdsInfo(vo);
    		ret.put("flag", "success");
    	}
    	return ret;
    }
    @RequestMapping(value="/deleGdsPic")
    @ResponseBody
    public Map<String,String> deleGdsPic(Model model, GdsInfoVO vo) throws Exception{
    	Map<String,String> ret = new HashMap<>();
    	ret.put("flag", "fail");
    	if(StringUtils.isNotEmpty(vo.getImage())){
    		gdsInfoSV.deleGdsPic(vo);
    		ret.put("flag", "success");
    	}
    	return ret;
    }
}
